package com.mt.mtyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.mtyx.acl.mapper.PermissionMapper;
import com.mt.mtyx.acl.mapper.RolePermissionMapper;
import com.mt.mtyx.acl.service.PermissionService;
import com.mt.mtyx.common.utils.Tree;
import com.mt.mtyx.entity.acl.Permission;
import com.mt.mtyx.entity.acl.RolePermission;
import com.mt.mtyx.entity.base.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WMT
 * @Date 2023/7/17 11:47
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;


    @Override
    public List<Permission> getAllPermission() {
        // 1.查询所有菜单
        List<Permission> all = baseMapper.selectList(null);

        // 2.生成树形结构
        return Tree.buildTree(all);
    }

    @Override
    public int insert(Permission permission) {
        return baseMapper.insert(permission);
    }

    @Override
    public int update(Permission permission) {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getId, permission.getId());
        permission.setUpdateTime(LocalDateTime.now());
        return baseMapper.update(permission, wrapper);
    }

    @Override
    public int removeChildById(Long id) {

        // 1.封装一个所有要删除的菜单的id的List
        List<Long> ids = new ArrayList<>();
        ids.add(id);

        // 2.获取当前菜单的所有子菜单
        this.getChild(id, ids);

        // 3.批量删除
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public Map<String, Object> getPermissionByRoleId(Long roleId) {
        // 1.查询所有权限
        List<Permission> allPermission = this.getAllPermission();

        // 2.查询已拥有的权限
        List<RolePermission> permissions = rolePermissionMapper.selectList(
                new QueryWrapper<RolePermission>().eq("role_id", roleId).select("permission_id")
        );

        List<Long> ids = null;
        if (permissions != null && !permissions.isEmpty()) {
            ids = permissions.stream()
                    .map(RolePermission::getPermissionId)
                    .collect(Collectors.toList());
        }

        // 3.已分配的权限
        List<Permission> list = new ArrayList<>();
        for (Permission permission : allPermission) {
            if (ids != null && !ids.isEmpty()) {
                if (ids.contains(permission.getId())) {
                    list.add(permission);
                }
            }
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedIds", list);
        map.put("allPermissions", allPermission);
        return map;
    }

    @Override
    public int setPermissionByRoleId(Long roleId, List<Long> permissionIds) {
        LocalDateTime now = LocalDateTime.now();
        // 1.先删除原有权限
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermission::getRoleId, roleId);
        rolePermissionMapper.delete(wrapper);

        // 2.重新分配权限
        List<RolePermission> list = permissionIds.stream()
                .map(data -> {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(data);
                    rolePermission.setCreateTime(now);
                    rolePermission.setUpdateTime(now);
                    rolePermission.setIsDeleted(BaseEntity.NOT_DELETED);
                    return rolePermission;
                })
                .collect(Collectors.toList());
        return rolePermissionMapper.batchSave(list);
    }

    /**
     * 获取所有子菜单
     *
     * @param id  当前菜单的id
     * @param ids 所有子菜单的id
     */
    private void getChild(Long id, List<Long> ids) {
        List<Permission> childList = baseMapper.selectList(
                new QueryWrapper<Permission>().eq("pid", id).select("id")
        );

        if (childList != null && !childList.isEmpty()) {
            childList.stream().forEach(data -> {
                ids.add(data.getId());
                this.getChild(data.getId(), ids);
            });
        }
    }
}
